package com.chuangjiangx.member.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StreamUtils;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;

/**
 * @author cj-ch
 * @date 2018/5/31 下午2:42
 */
public class MbrStringUtils {
    static final String EMOJI_PATTERN_STR ="[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]";
    static final Pattern EMOJI_PATTERN=Pattern.compile(EMOJI_PATTERN_STR);

    public static final String filterEmoji(String str){
        if(null == str || str.trim().length() < 1){
            return str;
        }
        return EMOJI_PATTERN.matcher(str).replaceAll("");
    }

    /**
     * 过滤掉超过3个字节的UTF8字符
     *
     * @param text
     * @return
     */
    public static String filterOffUtf8Mb4(String text)  {
        if(null == text ){
            return null;
        }
        if(text.trim().length() < 1){
            return "";
        }
        byte[] bytes = new byte[0];
        try {
            bytes = text.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        int i = 0;
        while (i < bytes.length) {
            short b = bytes[i];
            if (b > 0) {
                buffer.put(bytes[i++]);
                continue;
            }
            // 去掉符号位
            b += 256;

            if (((b >> 5) ^ 0x6) == 0) {
                buffer.put(bytes, i, 2);
                i += 2;
            } else if (((b >> 4) ^ 0xE) == 0) {
                buffer.put(bytes, i, 3);
                i += 3;
            } else if (((b >> 3) ^ 0x1E) == 0) {
                i += 4;
            } else if (((b >> 2) ^ 0x3E) == 0) {
                i += 5;
            } else if (((b >> 1) ^ 0x7E) == 0) {
                i += 6;
            } else {
                buffer.put(bytes[i++]);
            }
        }
        buffer.flip();
        return StringUtils.toEncodedString(buffer.array(),StandardCharsets.UTF_8);
    }

}
